package com.qf.user.manager.api;

import com.qf.common.bean.R;
import com.qf.common.model.QfUser;
import com.qf.common.utils.JwtUtil;
import com.qf.user.manager.bean.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.UUID;

/**
 * 管理员认证登录controller
 * @author 千锋健哥
 */
@RestController
@RequestMapping("/user/auth")
public class UserAuthController {

    //AuthenticationManager对象在SecurityConfig类中进行初始化, 这里注入使用
    //AuthenticationManager对象可以让SpringSecurity框架去自动调用UserDetailService实现类
    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 管理员登录
     * @param user
     * @return
     */
    @PostMapping("/doLogin")
    public R<String> login(@RequestBody QfUser user) {
        //1. 判断用户对象不为空
        if (user == null) {
            return R.fail("用户名和密码不可以为空!");
        }
        //2. 判断用户名, 密码不为空
        if(StringUtils.isEmpty(user.getUserName())
                || StringUtils.isEmpty(user.getPassword())) {
            return R.fail("用户名和密码不可以为空!");
        }

        //3. 调用SpringSecurity的UserDetailService实现类
        Authentication authenticate =
                authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserName(),
                        user.getPassword()));
        //4. 判断登录结果, 如果用户名密码错误, 返回异常信息, 登录失败
        if (authenticate == null) {
            return R.fail("认证失败!");
        }

        //5. 如果登录功能, 那么获取用户用户名
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userName = loginUser.getQfUser().getUserName();

        //6. 根据用户id生成jwt
        String jwt = JwtUtil.createJWT(UUID.randomUUID().toString(), userName, null);

        //7. 返回
        return R.ok(jwt);


    }
}
